package com.kn.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kn.common.config.jwt.JWTToken;
import com.kn.common.exception.UserException;
import com.kn.common.model.PageBean;
import com.kn.common.model.R;
import com.kn.common.model.RCode;
import com.kn.common.model.RPage;

import com.kn.sys.dao.RoleDao;
import com.kn.sys.dto.UserDto;
import com.kn.sys.mapper.UserMapper;
import com.kn.sys.model.User;
import com.kn.sys.model.UserExample;
import com.kn.sys.service.BaseService;
import com.kn.sys.service.UserService;
import com.kn.sys.untils.CopyBean;
import com.kn.sys.untils.JWTUtils;
import com.kn.sys.untils.MD5Utils;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouxp
 * @create 2021-03-04 11:24
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends BaseService implements UserService {

    private final UserMapper userMapper;
    private final RoleDao roleDao;
    @Override
    public R list(PageBean pageBean, String name) {
        UserExample example =new UserExample();
        UserExample.Criteria criteria = example.createCriteria()
                .andIsdelEqualTo(false);

        if(!StringUtils.isEmpty(name)){
            criteria.andCnameLike("%"+name+"%");
        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getSize());
        PageInfo<User> info =new PageInfo<>(userMapper.selectByExample(example));

        //List<UserDto> userDtos = new ArrayList<>();
        /*for (User user: info.getList()){
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
            userDtos.add(userDto);
        }*/
        /*info.getList().forEach(u->{
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(u,userDto);
            userDtos.add(userDto);
        });*/
        /*List<UserDto> userDtos = info.getList().stream().map(u -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(u, userDto);
            return userDto;
        }).collect(Collectors.toList());*/
        return R.ok(new RPage(info.getTotal(), CopyBean.copyBean(UserDto::new,info.getList())));
    }

    @Override
    public R add(UserDto userDto) {
    isExist(userDto);
        userMapper.insertSelective(CopyBean.copyBean(User::new,userDto));
        return R.ok();
    }

    @Override
    public R delete(Long id) {
        User user = new User();
        user.setId(id);
        user.setIsdel(true);
        userMapper.updateByPrimaryKeySelective(user);
        return R.ok();
    }

    @Override
    public R edit(Long id, UserDto userDto) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            throw new UserException(RCode.NOT_EXIST_USER);
        }
        BeanUtils.copyProperties(userDto,user);
        user.setId(id);
        user.setOptime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
        return R.ok();
    }

    @Override
    public R getRoleIdByUserId(Long userid) {
        return R.ok(roleDao.getRoleIdByUserId(userid));
    }

    @Override
    public R login(String username, String password) {

        UserExample example=new UserExample();
        example.createCriteria().andIsdelEqualTo(false)
                .andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(users)){
            throw new AuthenticationException("用户名或密码错误");
        }
        User user=users.get(0);
        String target= MD5Utils.md5Encryption(password,user.getUsername());
        String token= JWTUtils.sign(username, target);
        JWTToken jwtToken = new JWTToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
        }catch (AuthenticationException e){
            throw new AuthenticationException("token错误");
        }
        Map<String,Object> maps=new HashMap<>();
        maps.put("token",token);
        maps.put("perms",getActiveUser().getPermis());
        return R.ok(maps);
    }


    private void isExist(UserDto userDto) {
        UserExample userExample =new UserExample();
        userExample.createCriteria().andIsdelEqualTo(false)
                .andUsernameEqualTo(userDto.getUsername());
        long l = userMapper.countByExample(userExample);
        if(l>0){
            throw new UserException(RCode.EXIST_USER);
        }

    }
}
